package mysql

import (
	"time"

	"engine/eng_cfg"

	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

type cli struct {
	db *gorm.DB
}

func (ts *cli) start() (err error) {
	dbName := viper.GetString(eng_cfg.MysqlDBName)
	addr := viper.GetString(eng_cfg.MySqlAddr)
	user := viper.GetString(eng_cfg.MySqlUser)
	psw := viper.GetString(eng_cfg.MysqlPassword)
	dsn := user + ":" + psw + "@tcp(" + addr + ")/" + dbName + "?charset=utf8mb4&parseTime=True&loc=UTC&timeout=10s"

	mysqlConfig := mysql.Config{
		DSN:                       dsn,   // DSN data source name
		SkipInitializeWithVersion: false, // 根据版本自动配置
		DefaultStringSize:         127,
	}
	cfg := &gorm.Config{
		Logger: &myLogger{},
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   "",
			SingularTable: true, //   是否开启全局禁用复数，true表示开启
		},
		DisableForeignKeyConstraintWhenMigrating: true,
	}

	ts.db, err = gorm.Open(mysql.New(mysqlConfig), cfg)
	if err != nil {
		return err
	}
	//db.InstanceSet("gorm:table_options", "ENGINE=InnoDB")
	sqlDB, _ := ts.db.DB()
	sqlDB.SetMaxIdleConns(10)
	sqlDB.SetMaxOpenConns(100)
	sqlDB.SetConnMaxIdleTime(2 * time.Minute)
	return sqlDB.Ping()
}

func (ts *cli) stop() {
	ts.db = nil
}
